package _2022.hot100._79_单词搜索;

/**
 * @author： YHSimon
 * @date： 2022-04-19 10:51
 */
public class Solution {
    //上下左右移动的方向
    private static int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    public boolean exist(char[][] board, String word) {
        boolean[][] visited = new boolean[board.length][board[0].length];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, visited, word, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, boolean[][] visited, String word, int i, int j, int cur) {
        if (board[i][j] != word.charAt(cur)) {
            return false;
        } else if (cur == word.length() - 1) {
            return true;
        }


        boolean res = false;
        for (int[] dir : dirs) {
            int newi = i + dir[0], newj = j + dir[1];
            if (newi >= 0 && newi < board.length && newj >= 0 && newj < board[0].length) {
                if (!visited[newi][newj]) {
                    visited[i][j] = true;
                    boolean flag = dfs(board, visited, word, newi, newj, cur + 1);
                    if (flag) {
                        res = true;
                        break;
                    }
                    visited[i][j] = false;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.exist(new char[][]{{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}, "ABCCED"));
    }

}
